package com.heima.wemedia.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.heima.model.common.dtos.*;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.enums.WmMaterial;
import com.heima.model.wemedia.entity.WmNews;
import com.heima.model.wemedia.entity.WmNewsMaterial;
import com.heima.wemedia.Util.WmThreadLocalUtil;
import com.heima.wemedia.dao.WmMaterialDao;
import com.heima.wemedia.dao.WmNewsDao;
import com.heima.wemedia.dao.WmNewsMaterialDao;
import com.heima.wemedia.service.WmNewsService;
import org.apache.commons.lang.StringUtils;
import org.junit.Test;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 自媒体文章表(WmNews)表服务实现类
 *
 * @author makejava
 * @since 2022-04-12 15:48:48
 */
@Service("wmNewsService")
public class WmNewsServiceImpl implements WmNewsService {
    @Resource
    private WmNewsDao wmNewsDao;
    @Resource
    private WmNewsMaterialDao wmNewsMaterialDao;
    @Resource
    private WmMaterialDao wmMaterialDao;

    @Override
    public ResponseResult submitNews(WmNewsDto wmNewsDto) {
        //1. 参数校验
        if(StringUtils.isBlank(wmNewsDto.getContent())||StringUtils.
                isBlank(wmNewsDto.getTitle())){
          return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }
        //2. 封装数据
        WmNews news = new WmNews();
        //批量复制数据到目标对象 (属性名称和类型完成一致)  type : 布局类型    images : 封面图片
        BeanUtils.copyProperties(wmNewsDto,news);
        //2.1 抽取内容中的图片
        List<Map> contentList = JSON.parseArray(wmNewsDto.getContent(), Map.class);
        List<String> contentImages = contentList.stream().filter(map ->
                "image".equals(map.get("type"))).map(map -> map.get("value").
                toString()).collect(Collectors.toList());
        //2.2 抽取封面图片
        List<String> images = wmNewsDto.getImages();
        //2.3 封装type数据
        if(wmNewsDto.getType()==-1){
            if(contentImages.size()>=3){
                images = contentImages.stream().limit(3).collect(Collectors.toList());
                news.setType(3);
            }else if(contentImages.size()>0){
                images = contentImages.stream().limit(1).collect(Collectors.toList());
                news.setType(1);
            }else {
               images= Collections.EMPTY_LIST;
               news.setType(0);
            }

        }
        //2.4 封装封面图片数据
        if(CollectionUtils.isNotEmpty(images)){
            news.setImages(StringUtils.join(images,","));
        }
        //3. 保存文章数据  新增  修改
         saveNes(news);

        //4. 保存素材和文章的关联数据
        //4.1 保存文章和内容素材的引用关系
        saveContentImageRelation(news,contentImages);
        //4.2 保存文章和封面素材的引用关系
        saveCoverImageRelation(news,images);
        return ResponseResult.okResult("发布成功");

    }

    @Override
    public ResponseResult lsit(WmNewsPageReqDto page) {
        //1. 参数校验
       if(page==null){
           return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
       }
         page.checkParam();

        //2. 封装查询条件
        Map<String, Object> map = BeanUtil.beanToMap(page);
        map.put("userId",WmThreadLocalUtil.getUser().getId());

        //3. 执行查询
        PageHelper.startPage(page.getPage(), page.getSize());
        Page<WmNews> wmNews = wmNewsDao.queryByMap(map);

        //4. 封装数据返回
        ResponseResult result = new ResponseResult(page.getPage(), String.valueOf(page.getSize()), (int) wmNews.getTotal());
        return result;
    }

    @Override
    public ResponseResult delectById(Long id) {
        if(id==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章id不可缺少");
        }
        WmNews wmNews = wmNewsDao.queryById(id);
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        if(wmNews.getStatus()==9){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章已发布，不能删除");
        }
           wmNewsDao.deleteById(id);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    private void saveNes(WmNews news){

        news.setUserId(Long.valueOf(WmThreadLocalUtil.getUser().getId()));
        news.setCreatedTime(new Date());
        news.setEnable(1);
        //如果有id则修改，没有新增
        if(news.getId()==null){
             wmNewsDao.insert(news);

        }else{
            news.setUpdatedTime(new Date());
            wmNewsDao.update(news);
            wmNewsMaterialDao.deleteByNewsId(news.getId());
        }
        }
        //文章和内容素材图片引用
        private void saveContentImageRelation(WmNews news,List<String>contentImages){
            if(CollectionUtils.isEmpty(contentImages)){
              return;
            }
              saveNewsMaterial(news,contentImages,(short)1);
        }
        //文章和封面素材图片引用
        private void saveCoverImageRelation(WmNews news,List<String>contentImages){
           if(CollectionUtils.isEmpty(contentImages)){
               return;
           }
            saveNewsMaterial(news,contentImages,(short)0);
    }
    private void saveNewsMaterial(WmNews news,List<String>contentImages,Short type){
        if(news.getStatus()==0){
            return;
        }
        //1. 根据URL获取素材ID
        //1.1 查询素材列表

         contentImages=contentImages.stream().distinct().collect(Collectors.toList());
        List<WmMaterial> wmMaterials = wmMaterialDao.queryByUrls(contentImages);
        //1.2 提取素材ID
        List<Long> ids = wmMaterials.stream().map(wmMaterial -> wmMaterial.getId()).collect(Collectors.toList());

        //1.3 判断素材是否缺失
        if (ids.size() > ids.size()) {
            throw new RuntimeException("素材数据丢失!");
        }
        //2. 保存关联数据
        wmNewsMaterialDao.saveImageRelation(news.getId(), ids,type);
    }

}
